/**
 * @Date 2023-02-04 09:44:29
 * @Remark
 */

// react
import React from "react";
// lib
import {
  createBrowserRouter,
  IndexRouteObject,
  NonIndexRouteObject,
  RouteObject,
} from "react-router-dom";
// components & widget
import Index from "view/Index";
import Main from "view/Main";
import Login from "view/Login";
import NotFound from "view/NotFound";
import NotAccess from "view/NotAccess";
// config
import { ROUTE_LOGIN_VIEW, ROUTE_MAIN_VIEW, ROUTE_REGISTER_VIEW } from "project/config";
// script & methods & public
import MainRoutes from "./MainRoutes";
import Register from "view/Register";
// state
// interface
// 其它

// 获得路由组件列表,渲染视图
function createMainViewRouter() {
  const result: RouteObject[] = [];
  const loop = (list: AppRouteItem[]) => {
    list.forEach((el) => {
      if (el.children && el.children.length > 0) {
        // 如果有子菜单,本级菜单没有路由,做子菜单的路由
        loop(el.children);
      } else {
        // 没有子菜单
        if (el.index) {
          // 默认路由
          const it: IndexRouteObject = {
            index: true,
            element: el.component ? <el.component /> : undefined,
          };
          result.push(it);
        } else {
          // 不是默认路由
          const it: NonIndexRouteObject = {
            path: el.path,
            element: el.component ? <el.component /> : undefined,
            loader: el.loader,
          };
          result.push(it);
        }
      }
    });
  };
  // 递归
  loop(MainRoutes);
  // 最后加上无权限页面
  result.push({
    path: "system/403",
    element: <NotAccess />,
  });
  return result;
}

function createAppRouter() {
  const router = createBrowserRouter([
    {
      path: "/",
      element: <Index />,
      errorElement: <NotFound />,
    },
    {
      path: ROUTE_LOGIN_VIEW,
      element: <Login />,
      errorElement: <NotFound />,
      loader: async () => {
        return {};
      },
    },
    {
      path: ROUTE_REGISTER_VIEW,
      element: <Register />,
      errorElement: <NotFound />,
      loader: async () => {
        return {};
      },
    },
    {
      path: ROUTE_MAIN_VIEW,
      element: <Main />,
      errorElement: <NotFound />,
      loader: async () => {
        return {};
      },
      // 功能模块路由
      children: createMainViewRouter(),
    },
  ]);
  return router;
}

export default createAppRouter;
